package git.soulbgm.aspect;

import git.soulbgm.service.AlarmInfoReport;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

/**
 * 任务执行异常切面
 *
 * @author SoulBGM
 * @date 2023-01-06
 */
@Component
@Aspect
public class JobExceptionAspect {

    private final AlarmInfoReport report;

    public JobExceptionAspect(AlarmInfoReport report) {
        this.report = report;
    }

    @Pointcut("execution(* git.soulbgm.job.*.*.*(..))")
    public void allMethod() {}

    @AfterThrowing(value = "allMethod()", throwing = "ex")
    public void afterThrowingAlarm(Throwable ex) {
        StackTraceElement[] stackTrace = ex.getStackTrace();
        String className = "";
        for (StackTraceElement e : stackTrace) {
            String cn = e.getClassName();
            if (cn.startsWith("git.soulbgm.job")) {
                className = cn;
                break;
            }
        }
        report.jobExecuteExceptionAlarm(ex.getMessage(), className);
    }

}
